package com.config;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.*;
import java.io.File;
import java.util.EnumSet;

/**
 * @auther: zhangxin
 * @Description:  代替web.xml
 */
public class WebConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {

    // 创建Spring的ioc容器
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{SpringConfiguration.class};
    }

    // 创建SpringMVC的ioc容器
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{SpringMvcConfiguration.class};
    }

    // 将DispatcherServlet映射到"/"
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 首先要触发父类的onStartup，保证先初始化父类中的Web组件
        super.onStartup(servletContext);
        // 创建字符集过滤器对象
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        // 设置字符集
        encodingFilter.setEncoding("UTF-8");
        // 添加到Web容器（这不是Spring的ioc容器，而是ServletContainer）
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("characterEncodingFilter", encodingFilter);
        EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
        filterRegistration.addMappingForUrlPatterns(disps, true, "/*");

         /*
          配置CORS
         */
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //1) 定义允许的域。如果写成 *，则不能使用cookie
        //config.addAllowedOrigin("http://manage.leyou.com");
        //config.addAllowedOrigin("http://www.leyou.com");
        config.addAllowedOrigin("*");
        //2) 是否发送Cookie信息
        //config.setAllowCredentials(true);
        //3) 允许的请求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        config.setMaxAge(3600L);
        // 4）允许的头信息
        config.addAllowedHeader("*");

        //2.添加映射路径，我们拦截一切请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.注册CorsFilter
        registerServletFilter(servletContext, new CorsFilter(configSource));

    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        super.customizeRegistration(registration);

        // 临时文件的路径
        String location = "c:/tmp/";
        File file = new File(location);
        if(!file.exists() && !file.isDirectory()){
            file.mkdir();
        }
        // 上传参数
        long maxFileSize = 2097152; //2M
        long maxRequestSize = 4194304;  //4M
        int fileSizeThreshold = 0;

        //配置对multipart的支持
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(location, maxFileSize, maxRequestSize, fileSizeThreshold);
        registration.setMultipartConfig(multipartConfigElement);

        //设置404异常处理的参数，即有404异常时让DispatchServlet抛出throwExceptionIfNoHandlerFound
        registration.setInitParameter("throwExceptionIfNoHandlerFound","true");

    }




}
